<?php
namespace bdhert\PhpBitfield;

use bdhert\PhpBitfield\exception\CompareException;

/**
 * 参数比较
 * Class Compare
 * @package bdhert\PhpBitfield
 */
class Compare {
    private static $operator_maps = [
        '=' => 'EQU', '>' => 'GTR', '>=' => 'GEQ', '<' => 'LSS', 'LEQ' => '<=', '<>' => 'NEQ', 'between' => 'BETWEEN',
        'in' => 'IN'
    ];

    public static function operator($champion, $operator, $challenger) {
        $operator = strtolower($operator);
        $method   = self::$operator_maps[$operator] ?? '';
        if (!method_exists(self::class, $method))
            throw new CompareException('比较方法不存在', 400);

        return self::{$method}($champion, $challenger);
    }

    public static function EQU($champion, $challenger) {
        return $champion == $challenger;
    }

    public static function GTR($champion, $challenger) {
        return $champion > $challenger;
    }

    public static function GEQ($champion, $challenger) {
        return $champion >= $challenger;
    }

    public static function LSS($champion, $challenger) {
        return $champion < $challenger;
    }

    public static function LEQ($champion, $challenger) {
        return $champion <= $challenger;
    }

    public static function NEQ($champion, $challenger) {
        return $champion != $challenger;
    }

    public static function IN($champion, array $challenger) {
        return in_array($champion, $challenger);
    }

    public static function BETWEEN($champion, $challenger) {
        if (is_string($challenger)) $challenger = explode(',', $challenger);

        if (!is_array($challenger) || 2 !== count($challenger))
            throw new CompareException('比较范围格式错误', 400);

        [$start, $end] = $challenger;

        return ($champion >= $start) && ($champion < $end);
    }
}